#include "Character.hh"
#include <iostream>
#include <iomanip>
#include <algorithm>

Character::Character(std::string name, std::string desc, unsigned health, unsigned maxhealth, unsigned attack, unsigned defense,unsigned money)
    : name(name), description(desc), health(health), maxHealth(maxhealth), attacks(attack), defense(defense), money(money) {}

Character::~Character() {
    for (Item* item : inventory) {
        delete item;
    }
}

bool Character::isAlive() const
{
    return health>0;
}

bool Character::takeDamage(unsigned damage)
{
    if (damage >= health) {
        health = 0;
        std::cout << name << " has been defeated!\n";
        return true; 
    } else {
        health -= damage;
        return false;
    }
}

bool Character::attack(ICharacter& target) {
    unsigned damage = attacks;
    int actualDamage = static_cast<int>(damage) - static_cast<int>(target.getDefense());
    if (actualDamage < 0) actualDamage = 0;
    std::cout << name << " attacks " << target.getName() 
              << " for " << actualDamage << " damage!\n";
    return target.takeDamage(actualDamage);
}

void Character::addToInventory(Item* item) {
    inventory.push_back(item);
}



void Character::displayInventory() const {
    std::cout << "\nInventory:\n";
    for (size_t i = 0; i < inventory.size(); ++i) {
        std::cout << i + 1 << ". " << inventory[i]->getName() << " (" << inventory[i]->getDescription() << ")\n";
    }
}

std::string Character::toString() const {
    std::stringstream ss;
    ss << name << "\n"
       << "HP: " << health << "/" << maxHealth << "\n"
       << "ATK: " << attacks << "\n"
       << "DEF: " << defense << "\n";
       
    return ss.str();
}

void Character::display() const {
    std::cout << "\n=== " << name << " ===\n"
              << description << "\n"
              << toString();
}